<?php

namespace app\models;

use yii\base\Model;
use Yii;
use app\models\Config;
use yii\base\Exception;
use app\components\Fun;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BaseForm
 *
 * @author shuai
 */
class BaseForm extends Model {

    private static $_models = array();   // class name => model

    public static function model($className = __CLASS__) {
        if (isset(self::$_models[$className])) {   // echo 'isset***<br>';	
            return self::$_models[$className];
        } else { //  echo 'new:'.$className.'***<br>';
            return self::$_models[$className] = new $className(null);
        }
    }

    protected $houzhui = 'Base';

    //    private $config; 
    public function init() {
        // $this->config=new Config;
      
        $this->c_init();
        return parent::init();
    }

    private function c_init() {
        foreach ($this->get_data() as $key => $vo) {
            $this->$key = $vo;
        }
    }

    private function get_data() {
        ///   var_dump(Config::model());exit;


        $data = yii::$app->cache->get('BaseForm' . $this->houzhui);

        if ($data !== false)
            return $data;

        $data = [];
        $model = new Config;
     
        foreach ($this->attributeLabels() as $key => $vo) {

            $data[$key] = $model->get_val($key, $this->houzhui);
        }

        yii::$app->cache->set('BaseForm' . $this->houzhui, $data);

        return $data;
    }

    public function save() {
       

        $transaction = \Yii::$app->db->beginTransaction();
        try { 
            $model = new Config;
            $model->BaseForm = $this;
            foreach ($this->attributeLabels() as $key => $vo) {
                $model->set_val($key, $this->houzhui, $this->$key);
            }
            $transaction->commit();
             \app\components\Lcms::flush();
             return true;
        } catch (Exception $ex) { 
            Fun::showmsg($ex->getMessage());
            $transaction->rollBack(); ///回滚
        } 
        return true;
    }

}
